﻿using UnityEngine;
using System.Collections;

public class EnemyMove : MonoBehaviour {

	public Transform[] path = null;
	public float moveSpeed = 1.0f;
	public float rotationSpeed = 10.0f;

	int currentPathIndex = 0;
	Transform nextDestination = null;

	public Animation anim;
	public float walkAnimationSpeed = 1.0f;

	// Use this for initialization
	void Start () {
		path = MapManager.instance.GetPathArray ();

		FindNextDestination ();

		if (anim)
		{
			anim["Walk"].speed = walkAnimationSpeed;
			anim.Play ("Walk");
		}
	}

	void FindNextDestination()
	{
		if (currentPathIndex < path.Length)
		{
			nextDestination = path[currentPathIndex];

			if(currentPathIndex == 0)
				transform.position = nextDestination.position; // 적을 시작 위치로..

			++currentPathIndex;
		}
		else // 최종 목적 지점에 도달..
		{
			Destroy(gameObject);
		}
	}

	// Update is called once per frame
	void Update () {
		if (nextDestination == null)
			return;

		Vector3 targetPos = nextDestination.position;
		Vector3 myPos = transform.position;
		myPos.y = targetPos.y = 0.0f;

		float distance = (targetPos - myPos).magnitude;
		if (distance < 0.1f)
		{
			FindNextDestination();
		}
		else
		{
			Vector3 dir = nextDestination.position - transform.position;
			dir.y = 0.0f;
			dir.Normalize();

			transform.position += (dir * moveSpeed) * Time.deltaTime;
			Quaternion from = transform.rotation;
			Quaternion to = Quaternion.LookRotation(dir);
			transform.rotation = Quaternion.Lerp (from, to, rotationSpeed * Time.deltaTime);
		}
	}
}













